package com.tarena.lbs.attach.service.impl;

import com.tarena.lbs.attach.dao.repository.AttachRepository;
import com.tarena.lbs.attach.pojo.po.AttachPO;
import com.tarena.lbs.attach.pojo.vo.AttachVO;
import com.tarena.lbs.attach.pojo.vo.FileVO;
import com.tarena.lbs.attach.service.AttachService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class AttachServiceImpl implements AttachService {
    @Autowired
    private AttachRepository attachRepository;
    @Override
    public FileVO uploadAttach(MultipartFile file) throws IOException {
        log.info("上传附件名"+file);
        //获取原始文件名
        String fileName= file.getOriginalFilename();
        //获取文件名的后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        //创建新的文件名uuid
        fileName= UUID.randomUUID()+fileSuffix;

        //处理路径
        String dirPath="D:/files1";
        SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath=sdf.format(new Date());

        File dirFile=new File(dirPath+datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }

        String filePath=dirPath+datePath+fileName;
        file.transferTo(new File(filePath));

        FileVO fileVO=new FileVO();
        fileVO.setFileUuid(fileName);
        fileVO.setUrl(filePath);

        AttachPO attachPO=new AttachPO();
        BeanUtils.copyProperties(fileVO,attachPO);
        log.info("" +attachPO);
        log.info("" +fileVO);
        attachRepository.insert(attachPO);
        return fileVO;
    }
}
